//  Parameter details refer to:https://support.huaweicloud.com/api-ecs/zh-cn_topic_0020212668.html

resource "huaweicloud_compute_instance" "ecs" {
  count                       = var.ecs_configuration != null ? length(var.ecs_configuration) : 0
  image_id                    = var.image_id
  availability_zone           = var.availability_zone
  flavor_id                   = var.flavor_id
  security_group_ids          = [var.secgroup_id]
  name                        = var.name_suffix != "" ? format("%s-%s", lookup(element(var.ecs_configuration, count.index), "name"), var.name_suffix) : lookup(element(var.ecs_configuration, count.index), "name")
  system_disk_type            = lookup(element(var.ecs_configuration,count.index ), "system_disk_type")
  system_disk_size            = lookup(element(var.ecs_configuration,count.index ), "system_disk_size")
  charging_mode               = var.charging_mode
  period_unit                 = var.period_unit
  period                      = var.period
  stop_before_destroy         = lookup(element(var.ecs_configuration,count.index ), "stop_before_destroy")
  delete_disks_on_termination = lookup(element(var.ecs_configuration,count.index ), "delete_disks_on_termination")
  user_data                   = var.user_data
  network {
    uuid     = var.subnet_id
  }
  tags       = merge(
    { "Name" = var.name_suffix != "" ? format("%s-%s", lookup(element(var.ecs_configuration, count.index), "name"), var.name_suffix) : lookup(element(var.ecs_configuration, count.index), "name")},
    lookup(element(var.ecs_configuration, count.index), "tags")
  )
}

resource "huaweicloud_compute_eip_associate" "associated" {
  count        = var.associated_configuration !=null ? length(var.associated_configuration) : 0
  public_ip    = lookup(element(var.associated_configuration,count.index ), "public_ip")
  instance_id  = huaweicloud_compute_instance.ecs[count.index].id
}

